---
import { DevTools } from '@ag-website-shared/components/dev-tools/DevTools';
import { getEntry, type CollectionEntry } from 'astro:content';
import dsStylesUrl from '@design-system/design-system.scss?url';
import SiteHeader from '@ag-website-shared/components/site-header/SiteHeader.astro';
import { getFavIconsData, getAppleTouchIconsData } from '@utils/favicons';
import { getIsProduction, getIsArchive, getIsStaging, getIsDev } from '@utils/env';
import { urlWithBaseUrl } from '@utils/urlWithBaseUrl';
import Plausible from '@components/Plausible.astro';
import { Footer } from '@ag-website-shared/components/footer/Footer';
import styles from '@layouts/Layout.module.scss';
import { getApiPaths } from '@utils/apiMenuPath';
import { SITE_BASE_URL, PUBLIC_GTM_ID, PUBLIC_GTM_AUTH, PUBLIC_GTM_PREVIEW } from '@constants';
import GoogleTagManager from '@ag-website-shared/components/google-tag-manager/GoogleTagManager.astro';
import GoogleTagManagerBody from '@ag-website-shared/components/google-tag-manager/GoogleTagManagerBody.astro';

interface Props {
    title: string;
    description?: string;
    showSearchBar?: boolean;
    showDocsNav?: boolean;
    hideHeader?: boolean;
    hideFooter?: boolean;
    hidePageFromSearchEngines?: boolean;
}

const { data: metadata } = (await getEntry('metadata', 'metadata')) as CollectionEntry<'metadata'>;
const { data: apiNavData } = (await getEntry('apiNav', 'nav')) as CollectionEntry<'apiNav'>;

const { data: footerItems } = (await getEntry('footer', 'footer')) as CollectionEntry<'footer'>;
const apiPaths = getApiPaths(apiNavData);

const isProduction = getIsProduction();
const isArchive = getIsArchive();
const isStaging = getIsStaging();
const isDev = getIsDev();
const canonicalUrl = new URL(Astro.url.pathname, metadata.canonicalUrlBase);

const {
    title,
    description = metadata.description,
    showSearchBar,
    showDocsNav,
    hideHeader,
    hideFooter,
    hidePageFromSearchEngines,
} = Astro.props;

const path = Astro.url.pathname;
const socialImage = urlWithBaseUrl(metadata.socialImage);

const lightModeCSSUrl = `url("${urlWithBaseUrl('/images/sun.svg')}")`;
const darkModeCSSUrl = `url("${urlWithBaseUrl('/images/moon.svg')}")`;

const isHomepage = Astro.url.pathname.replaceAll('/', '') === SITE_BASE_URL.replaceAll('/', '');
---

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="description" content={description} />
        <meta name="viewport" content="width=device-width" />
        {
            getFavIconsData().map(({ size, icon }: any) => (
                <link rel="icon" type="image/png" sizes={`${size}x${size}`} href={icon} />
            ))
        }
        {
            getAppleTouchIconsData().map(({ size, icon }: any) => (
                <link rel="apple-touch-icon" sizes={`${size}x${size}`} href={icon} />
            ))
        }
        {(!isProduction || isArchive || hidePageFromSearchEngines) && <meta name="robots" content="noindex" />}
        <meta name="generator" content={Astro.generator} />
        <title>{title}</title>
        <link rel="canonical" href={canonicalUrl} />
        {
            !isDev && (
                <link
                    rel="sitemap"
                    type="application/xml"
                    title="Sitemap"
                    href={urlWithBaseUrl('/sitemap-index.xml')}
                />
            )
        }

        <!-- Import all global design system CSS -->
        <link rel="stylesheet" href={dsStylesUrl} />

        <!-- Facebook Meta Tags -->
        <meta property="og:url" content={canonicalUrl} />
        <meta property="og:type" content="website" />
        <meta property="og:title" content={title} />
        <meta property="og:description" content={description} />
        <meta property="og:image" content={socialImage} />

        <!-- Twitter Meta Tags -->
        <meta name="twitter:card" content="summary_large_image" />
        <meta property="twitter:domain" content={canonicalUrl.host} />
        <meta property="twitter:url" content={canonicalUrl} />
        <meta name="twitter:title" content={title} />
        <meta name="twitter:description" content={description} />
        <meta name="twitter:image" content={socialImage} />

        {
            !isDev && (
                <GoogleTagManager
                    googleTagManagerId={PUBLIC_GTM_ID}
                    googleTagManagerAuth={PUBLIC_GTM_AUTH}
                    googleTagManagerPreview={PUBLIC_GTM_PREVIEW}
                />
            )
        }
        {
            isProduction && (
                <Fragment>
                    <Plausible domain="ag-grid.com" />

                    <script async type="text/javascript" src="https://secure.inventiveinspired7.com/js/792251.js" />
                    <noscript>
                        <img alt="" src="https://secure.inventiveinspired7.com/792251.png" style="display:none;" />
                    </noscript>
                </Fragment>
            )
        }

        {isStaging && <Plausible domain="grid-staging.ag-grid.com" />}

        <style lang="scss" define:vars={{ lightModeCSSUrl, darkModeCSSUrl }}>
            :root {
                --dark-icon: var(--darkModeCSSUrl);
            }

            html[data-dark-mode='true'] {
                --dark-icon: var(--lightModeCSSUrl);
            }
        </style>
    </head>
    <body data-is-homepage={isHomepage}>
        <script is:inline>
            const htmlEl = document.querySelector('html');
            const localDarkmode = localStorage['documentation:darkmode'];
            const isOSDarkmode = (
                window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
            ).toString();

            if (localDarkmode === undefined) {
                localStorage.setItem('documentation:darkmode', isOSDarkmode);
            }

            htmlEl.classList.add('no-transitions');
            htmlEl.dataset.darkMode = localDarkmode !== undefined ? localDarkmode : isOSDarkmode;

            const getDarkmode = () => htmlEl.dataset.darkMode === 'true';
            htmlEl.dataset.agThemeMode = getDarkmode() ? 'dark-blue' : 'light';
            htmlEl.offsetHeight; // Trigger a reflow, flushing the CSS changes
            htmlEl.classList.remove('no-transitions');

            // Set up dark mode on change listeners
            const darkModeListeners = [];
            globalThis.addDarkmodeOnChange = (onChange) => {
                darkModeListeners.push(onChange);

                // Run once on initialisation
                onChange(getDarkmode());
            };

            // Listen to changes to html[data-dark-mode] attribute and notify listeners
            const observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    if (mutation.attributeName === 'data-dark-mode') {
                        const newDarkmode = getDarkmode();
                        darkModeListeners.forEach((listener) => {
                            listener(newDarkmode);
                        });
                    }
                });
            });
            observer.observe(htmlEl, { attributes: true });
        </script>

        <div id="mainContainer" class:list={styles.mainContainer}>
            {!hideHeader && <SiteHeader showSearchBar={showSearchBar} showDocsNav={showDocsNav} apiPaths={apiPaths} />}
            <slot />
        </div>

        {
            !hideFooter && (
                <Footer
                    client:load
                    showMicrosoftMessage={path === SITE_BASE_URL || path === undefined}
                    footerItems={footerItems}
                />
            )
        }
        <DevTools client:only />

        {
            !isDev && (
                <GoogleTagManagerBody
                    googleTagManagerId={PUBLIC_GTM_ID}
                    googleTagManagerAuth={PUBLIC_GTM_AUTH}
                    googleTagManagerPreview={PUBLIC_GTM_PREVIEW}
                />
            )
        }
    </body>
</html>
